<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax列表渲染示例</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            secondary: '#64748B',
            success: '#10B981',
            danger: '#EF4444',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        }
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
    }
  </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-6xl">
  <!-- 页面标题 -->
  <header class="mb-10 text-center">
    <h1 class="text-[clamp(1.8rem,4vw,2.8rem)] font-bold text-gray-800 mb-3">
      <i class="fa fa-list-alt text-primary mr-3"></i>数据列表展示
    </h1>
    <p class="text-gray-600 max-w-2xl mx-auto">
      页面加载时通过Ajax请求后端接口数据，并动态渲染展示列表内容
    </p>
  </header>

  <!-- 主要内容区 -->
  <main>
    <!-- 加载状态 -->
    <div id="loading" class="flex justify-center items-center py-20">
      <div class="text-center">
        <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
        <p class="text-gray-600">正在加载数据...</p>
      </div>
    </div>

    <!-- 错误提示 -->
    <div id="error" class="hidden bg-red-50 border border-red-200 text-red-700 px-6 py-4 rounded-lg mb-6">
      <div class="flex items-center">
        <i class="fa fa-exclamation-circle text-xl mr-3"></i>
        <div>
          <h3 class="font-medium">加载失败</h3>
          <p id="error-message" class="text-sm mt-1">无法获取数据，请稍后重试</p>
        </div>
      </div>
    </div>

    <!-- 数据统计信息 -->
    <div id="stats" class="hidden mb-6 bg-white rounded-lg p-4 card-shadow">
      <div class="flex flex-wrap justify-between items-center gap-4">
        <div>
          <p class="text-gray-500 text-sm">数据总数</p>
          <p id="total-count" class="text-2xl font-bold text-primary"></p>
        </div>
        <div>
          <p class="text-gray-500 text-sm">最后更新时间</p>
          <p id="last-update" class="text-lg text-gray-700"></p>
        </div>
        <button id="refresh-btn" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition flex items-center">
          <i class="fa fa-refresh mr-2"></i>刷新数据
        </button>
      </div>
    </div>

    <!-- 列表容器 -->
    <div id="list-container" class="hidden">
      <ul id="data-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <!-- 数据项将通过JavaScript动态插入 -->
      </ul>

      <!-- 空状态 -->
      <div id="empty-state" class="hidden py-20 text-center">
        <i class="fa fa-folder-open-o text-5xl text-gray-300 mb-4"></i>
        <p class="text-gray-500">没有找到任何数据</p>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="mt-16 text-center text-gray-500 text-sm">
    <p>© 2023 Ajax列表渲染示例 | 使用Tailwind CSS和原生JavaScript构建</p>
  </footer>
</div>

<script>
  // DOM元素引用
  const loadingElement = document.getElementById('loading');
  const errorElement = document.getElementById('error');
  const errorMessageElement = document.getElementById('error-message');
  const listContainerElement = document.getElementById('list-container');
  const dataListElement = document.getElementById('data-list');
  const emptyStateElement = document.getElementById('empty-state');
  const statsElement = document.getElementById('stats');
  const totalCountElement = document.getElementById('total-count');
  const lastUpdateElement = document.getElementById('last-update');
  const refreshBtn = document.getElementById('refresh-btn');

  // 模拟的API地址，实际项目中替换为真实接口地址
  const API_URL = 'api/invoices/index';

  // 页面加载完成后获取数据
  document.addEventListener('DOMContentLoaded', () => {
    fetchData();

    // 绑定刷新按钮事件
    refreshBtn.addEventListener('click', () => {
      fetchData();
    });
  });

  // 使用Ajax获取数据
  function fetchData() {
    // 显示加载状态，隐藏其他状态
    showLoading();

    // 创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();

    // 配置请求
    xhr.open('GET', API_URL, true);

    // 设置响应类型
    xhr.responseType = 'json';

    // 处理请求完成
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        // 请求成功，处理数据
        const data = xhr.response;
        renderData(data);
      } else {
        // 请求失败，显示错误
        showError(`请求失败，状态码: ${xhr.status}`);
      }
    };

    // 处理网络错误
    xhr.onerror = function() {
      showError('网络错误，无法连接到服务器');
    };

    // 发送请求
    xhr.send();
  }

  // 渲染数据列表
  function renderData(data) {
    // 清空现有列表
    dataListElement.innerHTML = '';

    // 更新统计信息
    totalCountElement.textContent = data.length;
    lastUpdateElement.textContent = new Date().toLocaleString();

    if (data.length === 0) {
      // 没有数据，显示空状态
      listContainerElement.classList.remove('hidden');
      statsElement.classList.remove('hidden');
      emptyStateElement.classList.remove('hidden');
      loadingElement.classList.add('hidden');
      return;
    }

    // 隐藏空状态
    emptyStateElement.classList.add('hidden');

    // 渲染列表项
    data.forEach(item => {
      const listItem = document.createElement('li');
      listItem.className = 'bg-white rounded-lg overflow-hidden card-shadow hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1';

      // 为了演示，我们使用JSONPlaceholder的posts数据结构
      // 实际项目中根据接口返回的数据结构调整
      listItem.innerHTML = `
                    <div class="p-6">
                        <div class="flex items-start mb-3">
                            <span class="bg-primary/10 text-primary text-xs font-semibold px-2.5 py-0.5 rounded-full mt-0.5">
                               发票类型：${item.type} || 发票号码: ${item.invoiceNumber}
                            </span>
                        </div>
                        <h3 class="text-xl font-bold mb-2 text-gray-800 line-clamp-2">开票日期：${item.date}</h3>
                        <p class="text-gray-600 text-sm mb-4 line-clamp-3">购买方：${item.buyer}</p>
                        <p class="text-gray-600 text-sm mb-4 line-clamp-3">销售方：${item.seller}</p>
                        <div class="flex justify-between items-center">
                            <span class="text-gray-500 text-xs">
                                <i class="fa fa-user mr-1"></i>金额：${item.amount}
                            </span>
                            <button class="text-primary hover:text-primary/80 text-sm font-medium flex items-center">
                                查看详情 <i class="fa fa-angle-right ml-1"></i>
                            </button>
                        </div>
                    </div>
                `;

      dataListElement.appendChild(listItem);
    });

    // 显示列表和统计信息，隐藏加载状态
    listContainerElement.classList.remove('hidden');
    statsElement.classList.remove('hidden');
    loadingElement.classList.add('hidden');
  }

  // 显示加载状态
  function showLoading() {
    loadingElement.classList.remove('hidden');
    errorElement.classList.add('hidden');
    listContainerElement.classList.add('hidden');
    statsElement.classList.add('hidden');
  }

  // 显示错误信息
  function showError(message) {
    errorMessageElement.textContent = message;
    errorElement.classList.remove('hidden');
    loadingElement.classList.add('hidden');
    listContainerElement.classList.add('hidden');
    statsElement.classList.add('hidden');
  }
</script>
</body>
</html>
